package org.dfl.core.data.types;

/**
 * a collection type with one fixed element's type
 * @author Piotr Wlodarczyk
 *
 */
public class CollectionType extends Type{
	private TypeContainer subtypeContainer;
	
	public CollectionType() {
		super();
		init(new AnyType());
	}

	public CollectionType(Type subtype) {
		super();
		init(subtype);
	}
	
	private void init(Type subtype){
		this.subtypeContainer = new TypeContainer(subtype);
	}

	
	@Override
	public boolean canMerge(Type t) {
		if(t == this) return true;
		// mozna polaczyc typ kolekcji z innym typem kolekcji jesli ich podtypy sa takie same
		if(t instanceof CollectionType &&
			((CollectionType)t).getSubtypeContainer().getType().canMerge(getSubtypeContainer().getType())){
			return true;
		}else if(t instanceof AnyType){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	public boolean complain(Type t) {
		if(t == this) return true;
		if(t instanceof CollectionType &&
			((CollectionType)t).getSubtypeContainer().connectWith(getSubtypeContainer())){
			mergeParentsWith(t);
			return true;
		}else if(t instanceof AnyType){
			return t.complain(this);
		}else{
			return false;
		}
	}
	
	public boolean complain(TypeContainer parent) {
		return complain(parent.getType());
	}

	@Override
	public Type getCopy() {
		return new CollectionType(getSubtypeContainer().getType().getCopy());
	}

	@Override
	public String save() {
		StringBuffer ret = new StringBuffer();
		ret.append("{");
		ret.append(subtypeContainer.getType().save());
		ret.append("}");
		return ret.toString();
	}

	public TypeContainer getSubtypeContainer() {
		return subtypeContainer;
	}
}
